﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using Besture.Common.Helper;

namespace Besture.Common.Solution
{
    public class AutoMaticHelper
    {
        ///// <summary>
        ///// 创建内容模型
        ///// </summary>
        ///// <param name="tableContentModel"></param>
        ///// <param name="tableContentModelField"></param>
        //public static void Create(DataTable tableContentModel, DataTable tableContentModelField)
        //{
        //    for (int i = 0; i < tableContentModel.Rows.Count; i++)
        //    {
        //        CreateManagePage(tableContentModel.Rows[i]["TableName"].ToString(),tableContentModelField);
        //    }
        //    SolutionManager.UpdateCsProj();
        //    SolutionManager.MsBuild();
        //}

        /// <summary>
        /// 创建管理页面
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="tableContentModelField"></param>
        public static void CreateManagePage(string tableName, DataTable tableContentModelField)
        {
            string AutoMaticPath = System.Web.HttpContext.Current.Server.MapPath("/Admin/CommonModel/AutoMatic/");

            #region 创建List页面

            //读取模板
            string listAspxContent = IoHelper.ReadFile("/Admin/Template/AutoMatic/ListAspx.txt");
            string listCsContent = IoHelper.ReadFile("/Admin/Template/AutoMatic/ListCs.txt");
            string listDesignerContent = IoHelper.ReadFile("/Admin/Template/AutoMatic/ListDesigner.txt");


            //修改模板文件
            listAspxContent = listAspxContent.Replace("{TableName}", tableName);
            listAspxContent = listAspxContent.Replace("{ModelName}", "");

            string columnStr = string.Empty;
            for (int i = 0; i < tableContentModelField.Rows.Count; i++)
            {
                columnStr += GetGridViewDataTextColumnStr(tableContentModelField.Rows[i], i + 3);
            }
            //列表页面显示字段
            listAspxContent = listAspxContent.Replace("{Column}", columnStr);
            listCsContent = listCsContent.Replace("{TableName}", tableName);
            listDesignerContent = listDesignerContent.Replace("{TableName}", tableName);

            //生成文件
            CreateFile(AutoMaticPath, "USER_" + tableName + "List.aspx", listAspxContent);
            CreateFile(AutoMaticPath, "USER_" + tableName + "List.aspx.cs", listCsContent);
            CreateFile(AutoMaticPath, "USER_" + tableName + "List.aspx.designer.cs", listDesignerContent);

            #endregion


            #region 创建Set页面

            //读取模板
            string setAspxContent = IoHelper.ReadFile("/Admin/Template/AutoMatic/SetAspx.txt");
            string setCsContent = IoHelper.ReadFile("/Admin/Template/AutoMatic/SetCs.txt");
            string setDesignerContent = IoHelper.ReadFile("/Admin/Template/AutoMatic/SetDesigner.txt");

            //修改模板文件
            setAspxContent = setAspxContent.Replace("{TableName}", tableName);
            setCsContent = setCsContent.Replace("{TableName}", tableName);
            setDesignerContent = setDesignerContent.Replace("{TableName}", tableName);

            setAspxContent = LoadSetAspx(setAspxContent, tableName, tableContentModelField);
            setCsContent = LoadSetCs(setCsContent, tableName, tableContentModelField);
            setDesignerContent = LoadSetCs(setDesignerContent, tableName, tableContentModelField);

            //生成文件
            CreateFile(AutoMaticPath, "USER_" + tableName + "Set.aspx", setAspxContent);
            CreateFile(AutoMaticPath, "USER_" + tableName + "Set.aspx.cs", setCsContent);
            CreateFile(AutoMaticPath, "USER_" + tableName + "Set.aspx.designer.cs", setDesignerContent);

            #endregion


        }

        /// <summary>
        /// 生成文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="content"></param>
        public static void CreateFile(string filePath, string fileName, string content)
        {
            System.IO.StreamWriter streamWriterListAspx = new StreamWriter(filePath + fileName, false, Encoding.UTF8);// System.IO.File.CreateText(filePath + fileName);
            streamWriterListAspx.Write(content);
            streamWriterListAspx.Dispose();
            streamWriterListAspx.Close();
        }


        /// <summary>
        /// 获取LIST显示内容
        /// </summary>
        /// <param name="row"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        public static string GetGridViewDataTextColumnStr(DataRow row, int rowIndex)
        {
            string str = string.Empty;
            //字段类型
            int fieldType = Convert.ToInt32(row["FieldType"].ToString());
            switch (fieldType)
            {
                //单行文本
                case 1:
                    if (DisplayWidth(row["ListDisplay"]))
                    {
                         str =
                        string.Format(
                            @" <cms:GridViewDataTextColumn Caption=""{0}"" VisibleIndex=""{1}"" HeaderStyle-HorizontalAlign=""Center"" CellStyle-HorizontalAlign=""Center"" FieldName=""{2}"" {3}><Settings AutoFilterCondition=""Contains""></Settings></cms:GridViewDataTextColumn>",
                            row["Alias"], rowIndex, row["Name"], GetWidthString(Convert.ToInt32(row["ListDisplay"])));
                    }
                   
                    break;
                //多行文本
                case 2:
                    if (DisplayWidth(row["ListDisplay"]))
                    {
                        str =
                            string.Format(
                                @" <cms:GridViewDataTextColumn Caption=""{0}"" VisibleIndex=""{1}"" HeaderStyle-HorizontalAlign=""Center"" CellStyle-HorizontalAlign=""Center"" FieldName=""{2}"" {3}><Settings AutoFilterCondition=""Contains""></Settings></cms:GridViewDataTextColumn>",
                                row["Alias"], rowIndex, row["Name"], GetWidthString(Convert.ToInt32(row["ListDisplay"])));
                    }
                    break;
                //富文本
                case 3:
                    //复文本不显示
                    str = "";
                    break;
                //选项
                case 4:
                    str = "";
                    break;
                //图片
                case 5:
                    str = "";
                    break;
                //文件
                case 6:
                    //文件不显示
                    str = "";
                    break;
                case 7:
                    if (DisplayWidth(row["ListDisplay"]))
                    {
                        str =
                            string.Format(
                                @"                <cms:GridViewDataDateColumn Caption=""{0}"" VisibleIndex=""{1}""  HeaderStyle-HorizontalAlign=""Center""
                                                                            CellStyle-HorizontalAlign=""Center"" FieldName=""{2}"" {3}>
                                                                            <PropertiesDateEdit DisplayFormatString=""[0:yyyy-MM-dd]"">
                                                                            </PropertiesDateEdit>
                                                                        </cms:GridViewDataDateColumn>
                                                        ",
                                row["Alias"], rowIndex, row["Name"], GetWidthString(Convert.ToInt32(row["ListDisplay"])));
                    }
                    str = str.Replace("[0:yyyy-MM-dd]", "{0:yyyy-MM-dd}");
                    break;
            }
            return str;
        }

        /// <summary>
        /// 获取列宽度
        /// </summary>
        /// <param name="width"></param>
        /// <returns></returns>
        public static string GetWidthString(int width)
        {
            //当值为999时，表示为自动适应宽度
            string widthStr = string.Empty;
            if (width != 999)
            {
                widthStr = string.Format(@" Width=""{0}px""", width);
            }
            return widthStr;
        }
        /// <summary>
        /// 判断是否显示宽度
        /// </summary>
        /// <param name="width"></param>
        /// <returns></returns>
        public static bool DisplayWidth(object width)
        {
            bool flag = true;
            //过滤掉不显示的情况
            if(width == null)
            {
                flag = false;
            }
            if(string.IsNullOrEmpty(width.ToString()))
            {
                flag = false;
            }
            if(width.ToString().Equals("0"))
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 加载模板文件 ASPX
        /// </summary>
        /// <param name="setAspxContent"></param>
        /// <param name="tableName"></param>
        /// <param name="tableContentModelField"></param>
        /// <returns></returns>
        public static string LoadSetAspx(string setAspxContent, string tableName, DataTable tableContentModelField)
        {
            setAspxContent = setAspxContent.Replace("{TableName}", tableName);

            string trColumnStr = string.Empty;
            for (int i = 0; i < tableContentModelField.Rows.Count; i++)
            {
                DataRow row = tableContentModelField.Rows[i];
                //字段类型
                int fieldType = Convert.ToInt32(row["FieldType"].ToString());
                switch (fieldType)
                {
                    //单行文本
                    case 1:
                        trColumnStr +=
                            string.Format(
                                @"<tr>
                                      <th>
                                          {0}：
                                      </th>
                                      <td>
                                          <cms:TextBox runat=""server"" ID=""{1}"" WidthExt=""Width_{2}""  Required=""{3}""  MaxLength=""{4}"" {5}></cms:TextBox>
                                      </td>
                                  </tr>", row["Alias"], row["Name"], row["TextBoxWidth"], row["Required"].ToString().Equals("1") ? "True" : "False", row["MaxLength"], "");
                        break;
                    //多行文本
                    case 2:
                        trColumnStr +=
                            string.Format(
                                @"<tr>
                                      <th>
                                          {0}：
                                      </th>
                                      <td>
                                          <cms:TextBox runat=""server"" ID=""{1}""  Required=""{2}""  TextMode=""MultiLine"" Width=""{3}"" Height=""{4}""></cms:TextBox>
                                      </td>
                                  </tr>", row["Alias"], row["Name"], row["Required"].ToString().Equals("1") ? "True" : "False", row["DisWidth"], row["DisHeight"]);
                        break;
                    //富文本
                    case 3:
                        trColumnStr +=
                           string.Format(
                               @"<tr>
                                      <th>
                                          {0}：
                                      </th>
                                      <td>
                                         <cms:RichText ID=""{1}"" runat=""server"" RichTextName=""{1}text""  Width=""{2}"" Height=""{3}""></cms:RichText>
                                      </td>
                                  </tr>", row["Alias"], row["Name"], row["DisWidth"], row["DisHeight"]);
                        break;
                    //选项
                    case 4:

                        break;
                    //图片
                    case 5:
                        trColumnStr +=
                           string.Format(
                               @"<tr>
                                      <th>
                                          {0}：
                                      </th>
                                      <td>
                                          <cms:UploadSinglePhoto ID=""{1}"" runat=""server"" Required=""{2}"" FolderPath=""{3}"" Tips=""{4}""  />
                                      </td>
                                  </tr>", row["Alias"], row["Name"], row["Required"].ToString().Equals("1") ? "True" : "False", row["PhotoPath"], row["Tips"]);
                        break;
                    //文件
                    case 6:

                        break;
                    //时间
                    case 7:
                        var text = string.Empty;
                        //默认时间
                        if (row["IsDefaultTime"].ToString().Equals("1"))
                        {
                            text = DateTimeHelper.FormatStandard();
                        }
                        trColumnStr +=
                            string.Format(
                                @"<tr>
                                      <th>
                                          {0}：
                                      </th>
                                      <td>
                                         <cms:TextBox runat=""server"" ID=""{1}"" WidthExt=""Width_{2}"" ValidateExt=""Date""  Required=""{3}"" Text=""{4}"" ></cms:TextBox>
                                      </td>
                                  </tr>", row["Alias"], row["Name"], row["TextBoxWidth"], row["Required"].ToString().Equals("1") ? "True" : "False", text);
                        break;
                }
            }

            setAspxContent = setAspxContent.Replace("{TrColumn}", trColumnStr);
            return setAspxContent;
        }

        /// <summary>
        /// 加载模板文件 CS
        /// </summary>
        /// <param name="setAspxContent"></param>
        /// <param name="tableName"></param>
        /// <param name="tableContentModelField"></param>
        /// <returns></returns>
        public static string LoadSetCs(string setAspxContent, string tableName, DataTable tableContentModelField)
        {
            setAspxContent = setAspxContent.Replace("{TableName}", tableName);

            string initDataColumnStr = string.Empty;

            string insertSqlColumnStr = string.Empty;
            string insertParamColumnStr = string.Empty;
            string insertSetParamColumn = string.Empty;

            string updateSqlColumnStr = string.Empty;
            string updateSetParamColumn = string.Empty;

            string designerColumn = string.Empty;

            for (int i = 0; i < tableContentModelField.Rows.Count; i++)
            {
                DataRow row = tableContentModelField.Rows[i];

                insertSqlColumnStr += string.Format(@"{0},", row["name"]);
                insertParamColumnStr += string.Format(@"@{0},", row["name"]);
                updateSqlColumnStr += string.Format(@"{0} = @{0},", row["name"]);

                //字段类型
                int fieldType = Convert.ToInt32(row["FieldType"].ToString());
                switch (fieldType)
                {
                    //单行文本
                    case 1:
                        initDataColumnStr += string.Format(@"{0}.Text = row[""{0}""].ToString();", row["Name"]);
                        insertSetParamColumn +=
                            string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.Text);",
                                row["Name"]);
                        updateSetParamColumn += string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.Text);",
                                row["Name"]);
                        designerColumn += string.Format(@"protected global::Besture.CmsControl.TextBox {0};", row["Name"]);
                        break;
                    //多行文本
                    case 2:
                        initDataColumnStr += string.Format(@"{0}.Text = row[""{0}""].ToString();", row["Name"]);
                        insertSetParamColumn +=
                            string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.Text);",
                                row["Name"]);

                        updateSetParamColumn += string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.Text);",
                                row["Name"]);

                        designerColumn += string.Format(@"protected global::CmsControl.TextBox {0};", row["Name"]);
                        break;
                    //富文本
                    case 3:
                        initDataColumnStr += string.Format(@"{0}.Text = row[""{0}""].ToString();", row["Name"]);
                        insertSetParamColumn +=
                            string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.Text);",
                                row["Name"]);

                        updateSetParamColumn += string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.Text);",
                                row["Name"]);

                        designerColumn += string.Format(@"protected global::Besture.UI.Admin.Control.RichText {0};", row["Name"]);
                        break;
                    //选项
                    case 4:
                        insertSetParamColumn +=
                            string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, """");", row["Name"]
                                );
                        updateSetParamColumn += string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, """");", row["Name"]);

                        break;
                    //图片
                    case 5:
                        initDataColumnStr += string.Format(@"{0}.ImageUrl = row[""{0}""].ToString();", row["Name"]);
                        insertSetParamColumn +=
                            string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.ImageUrl);",
                                row["Name"]);

                        updateSetParamColumn += string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.String, {0}.ImageUrl);",
                                row["Name"]);

                        designerColumn += string.Format(@"protected global::Besture.UI.Admin.Control.UploadSinglePhoto {0};", row["Name"]);
                        break;
                    //文件
                    case 6:

                        break;
                    case 7:
                        initDataColumnStr += string.Format(@"{0}.Text = DateTime.Parse(row[""{0}""].ToString()).ToString(""yyyy-MM-dd"");", row["Name"]);
                        insertSetParamColumn +=
                            string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.DateTime, Convert.ToDateTime({0}.Text));",
                                row["Name"]);

                        updateSetParamColumn += string.Format(
                                @"baseDataAccess.SetParameter(ldcDBCommand, ""@{0}"", DbType.DateTime,  Convert.ToDateTime({0}.Text));",
                                row["Name"]);
                        designerColumn += string.Format(@"protected global::CmsControl.TextBox {0};", row["Name"]);
                        break;
                }
            }

            setAspxContent = setAspxContent.Replace("{InitDataColumn}", initDataColumnStr);

            setAspxContent = setAspxContent.Replace("{InsertSqlColumn}", insertSqlColumnStr.TrimEnd(','));
            setAspxContent = setAspxContent.Replace("{InsertParamColumn}", insertParamColumnStr.TrimEnd(','));
            setAspxContent = setAspxContent.Replace("{InsertSetParamColumn}", insertSetParamColumn);

            setAspxContent = setAspxContent.Replace("{UpdateSqlColumn}", updateSqlColumnStr.TrimEnd(','));
            setAspxContent = setAspxContent.Replace("{UpdateSetParamColumn}", updateSetParamColumn);

            setAspxContent = setAspxContent.Replace("{DesignerColumn}", designerColumn);



            return setAspxContent;
        }

        /// <summary>
        /// 加载模板文件  Designer
        /// </summary>
        /// <param name="setAspxContent"></param>
        /// <param name="tableName"></param>
        /// <param name="tableContentModelField"></param>
        /// <returns></returns>
        public static string LoadSetDesigner(string setAspxContent, string tableName, DataTable tableContentModelField)
        {
            setAspxContent = setAspxContent.Replace("{TableName}", tableName);


            string designerColumn = string.Empty;

            for (int i = 0; i < tableContentModelField.Rows.Count; i++)
            {
                DataRow row = tableContentModelField.Rows[i];

                //字段类型
                int fieldType = Convert.ToInt32(row["FieldType"].ToString());
                switch (fieldType)
                {
                    //单行文本
                    case 1:

                        designerColumn += string.Format(@"protected global::CmsControl.TextBox {0};", row["Name"]);
                        break;
                    //多行文本
                    case 2:
                        designerColumn += string.Format(@"protected global::CmsControl.TextBox {0};", row["Name"]);
                        break;
                    //富文本
                    case 3:

                        designerColumn += string.Format(@"protected global::Besture.UI.Admin.Control.RichText {0};", row["Name"]);
                        break;
                    //选项
                    case 4:

                        break;
                    //图片
                    case 5:

                        designerColumn += string.Format(@"protected global::Besture.UI.Admin.Control.UploadSinglePhoto {0};", row["Name"]);
                        break;
                    //文件
                    case 6:

                        break;
                    //日期控件
                    case 7:
                        designerColumn += string.Format(@"protected global::CmsControl.TextBox {0};", row["Name"]);
                        break;
                }
            }


            setAspxContent = setAspxContent.Replace("{DesignerColumn}", designerColumn);

            return setAspxContent;
        }
    }
}
